import React from 'react';
import Item from './components/caseItem'
import useTitle from '../../hooks/useTitle';
import { useState, useEffect } from 'react'
import './index.css';
import axios from 'axios';
import HOST from '../../utils/const';

function Question() {
  useTitle(Question.title);
  const [detail, setDetail] = useState([]);
  const [pageSize, setPageSize] = useState(3);
  const [change, setChange] = useState(false);
  const [pageNum, setPageNum] = useState(1);
  const [create, setCreate] = useState(false);
  const [currentInfo, setCurrentInfo] = useState(getCurrentInfo());

  function createNewQuestion(){
    const question = document.getElementById('case-create-name-question').value;
    const answer1 = document.getElementById('case-create-1').value;
    const answer2 = document.getElementById('case-create-2').value;
    const answer3 = document.getElementById('case-create-3').value;
    const answer4 = document.getElementById('case-create-4').value;
    const right = document.getElementById('answer-right').value;
    const subject = document.getElementById('subject-choose').value;
    if(!(question && answer1 && answer2 && answer3 && answer4 && right)){
      alert('请将题目补充完整');
      return;
    }
    if(!['A','B','C','D'].includes(right.toUpperCase && right.toUpperCase())){
      alert('请填写格式正确的答案');
      return;
    }
    console.log(question , answer1 , answer2 , answer3 , answer4 , right, subject);
    axios.post(HOST + `/method/form`, JSON.stringify({
      case:2,
      class: subject,
      content: question+ '$'+ answer1 + '$'+ answer2 + '$'+ answer3 + '$'+ answer4,
      answer: right
    })).then((res) => {
      switch (res.data) {
        case 'code=15\n': {
          alert('新增失败');
          setChange(!change);
          break;
        }
        case 'code=16\n': {
          alert('新增成功');
          setChange(!change);
          break;
        }
        default: {
          alert('未知错误');
          break;
        }
      }
    }).catch((err) => {
      console.log(err);
    });
    setCreate(false);
  }
  function remove(index){
    axios.get(HOST+`/method/monitor?case=9&id=${index}`).then((res)=>{
      switch (res.data) {
        case 'code=17\n' :{
          alert('删除成功');
          setChange(!change);
          break;
        }
        case 'code=18\n' :{
          alert('删除失败');
          setChange(!change);
          break;
        }
        default: {
          alert('未知错误');
          break;
        }
      }
    }).catch((err)=>{
      console.log(err);
    });
    
  }
  function getCurrentInfo() {
    return detail.slice(pageSize * (pageNum - 1), pageSize * pageNum);
  }
  function updateCurrentInfo(size, num) {
    const res = detail.slice(pageSize * (num - 1), pageSize * num);
    if (res.length === 0) {
      const lastPage = Math.ceil(detail.length / pageSize);
      console.log(lastPage)
      setPageNum(lastPage);
      setPageSize(size)
    } else {
      setPageSize(size);
      setPageNum(num);
    }
  }
  useEffect(() => {
    axios.get(HOST+`/method/monitor?case=7`).then((res)=>{
      switch (res.data.split('\n')[0]) {
        case 'code=21' :{
          const res2 = solve(res.data.slice(8).split('\n'))
          console.log(res2);
          
          setDetail(res2);
          break;
        }
        default: {
          alert('未知错误');
          break;
        }
      }
    }).catch((err)=>{
      console.log(err);
    });
  }, [ change ])
  function solve(str){
    const res = []
    for(let item of str){
      if(!item) break;
      const mid = item.split('\t');
      const qanda = mid[2].split('$');
      res.push({
        id: mid[0],
        subject: mid[1],
        answer: mid[3],
        question: qanda[0],
        answers: [qanda[1].split('=').pop(),qanda[2].split('=').pop(),qanda[3].split('=').pop(),qanda[4].split('=').pop()]
      })
    }
    return res;
  }
  function nextPage() {
    const lastPage = Math.ceil(detail.length / pageSize);
    if (pageNum === lastPage) {
      return
    }
    setPageNum(pageNum + 1)
  }

  function lastPage() {
    setPageNum(pageNum - 1)
  }

  useEffect(() => {
    setCurrentInfo(getCurrentInfo());
    // eslint-disable-next-line
  }, [pageSize, pageNum, detail])
  return (
    <div className='study'>
            <div className="mask" style={create ? { display: 'block' } : { display: 'none' }}></div>
      <div className='detail-case' style={create ? { display: 'block' } : { display: 'none' }}>
        <div className='detail-case-topbar'>
          <input  type="text"
            id='case-create-name-question'
            placeholder='请输入题干' />
        </div>
        <div className='question-case-content'>
          <div className='detail-case-content-item'>
            <div className='detail-case-content-name'>A</div>
            <input  type="text"
              className='question-case-content-text' id='case-create-1' />
          </div>
          <div className='detail-case-content-item'>
            <div className='detail-case-content-name'>B</div>
            <input  type="text"
              className='question-case-content-text' id='case-create-2' />
          </div>
          <div className='detail-case-content-item'>
            <div className='detail-case-content-name'>C</div>
            <input  type="text"
              className='question-case-content-text' id='case-create-3' />
          </div>
          <div className='detail-case-content-item'>
            <div className='detail-case-content-name'>D</div>
            <input  type="text"
              className='question-case-content-text' id='case-create-4' />
          </div>
        </div>
        <input type="text" placeholder='请输入正确答案' className='right-answer' id='answer-right'/>
        <select name="subject" id="subject-choose" className='choose-subject'>
          <option value="math" >内科</option>
          <option value="physical">外科</option>
        </select>
        <div className='question-case-footbutton' 
          onClick={createNewQuestion}>新建</div>
      </div>
      <div className='study-topbar'>
      <div className='check-button-create'   onClick={() => { setCreate(true) }}>新建试题</div>
      </div>
      <div className='study-detail'>
        <div className='question-study-detail-topbar'>
          <div className='question-detail-subject'>科目</div>
          <div className='question-detail-question'>题干</div>
          <div className='question-detail-answers'>选项</div>
          <div className='question-detail-right'>正确选项</div>
          <div className='question-detail-operation'>操作</div>
        </div>
        {currentInfo.map((item, index) => <Item detail={item} key={item.question+item.subject} id={index} remove={remove} />)}
        <div className='study-detail-footbar'>
          <div className='case-total'>共 {detail.length} 条</div>
          <div className='case-pagesize'>
            <select className='pagesize-select' name='pagesize' id='pagesize' onChange={() => {
              updateCurrentInfo(Number(document.getElementById("pagesize").value), pageNum)
            }}>
              <option value="3">3条/页</option>
              <option value="6">6条/页</option>
              <option value="10">10条/页</option>
            </select>
          </div>
          <div className='change-page'>
            <div className='last-page'>
              <div className='left-arrow' onClick={lastPage}></div>
            </div>
            <div className='current-page'>{pageNum}</div>
            <div className='next-page'>
              <div className='right-arrow' onClick={nextPage}></div>
            </div>
          </div>
          <div className='goto-page'>
            前往<input type="text" id='target-page' onBlur={
              (e) => {
                const res = Number(e.target.value)
                console.log(res);
                if (Number.isInteger(res)) {
                  const target = Math.round(res);
                  updateCurrentInfo(pageSize, target)
                }
              }
            } />页
      </div>
        </div>
      </div>
    </div>
  );
}

Question.path = '/question';
Question.title = '学习病例';
Question.meta = {
  keywords:
    '学习病例',
  description:
    '宠物医院 学习知识'
};
Question.exact = true;

export default Question;
